package com.zhp.processor;

import org.springframework.context.expression.MethodBasedEvaluationContext;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.core.ParameterNameDiscoverer;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;

import java.lang.reflect.Method;

/**
 * @author zhanghp
 * @since 2024/5/24 13:56
 */
public class NameSpelExpressionProcessor implements NameProcessor {

    /**
     * 参数发现器
     */
    private final ParameterNameDiscoverer parameterNameDiscoverer = new DefaultParameterNameDiscoverer();

    /**
     * Express语法解析器
     */
    private final ExpressionParser expressionParser = new SpelExpressionParser();

    @Override
    public String doDetermineName(Object[] args, Method method, String key) {
        if (!key.contains("#")) {
            return key;
        }
        MethodBasedEvaluationContext context = new MethodBasedEvaluationContext(null, method, args, parameterNameDiscoverer);
        return expressionParser.parseExpression(key).getValue(context, String.class);
    }
}
